package com.wzf.greattruth.zookeeper.node;

import java.io.Serializable;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author wuzhengfei
 *
 */
public class Node implements Comparable<Node>, Serializable {
    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = LoggerFactory.getLogger(Node.class);
    private static final String SEPARATOR = "-";
    private String id;
    private String dir;
    private String prefix;
    private int sequence = 0;

    public Node(String dir, String id) {
        this(dir, id, null);
    }

    public Node(String dir, String id, String prefix) {
        super();
        if (StringUtils.isBlank(dir) || StringUtils.isBlank(id)) {
            throw new NullPointerException("id or dir cannot be null");
        }
        this.dir = dir;
        this.id = id;
        this.prefix = prefix;

        init();
    }

    private void init() {
        String value = id;
        if (!StringUtils.isBlank(prefix)) {
            if (!id.startsWith(prefix)) {
                throw new IllegalArgumentException("id need start with prefix! id=" + id + "  prefix=" + prefix);
            }
            value = value.substring(prefix.length());
        }
        try {
            this.sequence = Integer.parseInt(value);
        } catch (NumberFormatException e) {
            LOGGER.error("NumberFormatException id={}", id, e);
        }
    }

    public int compareTo(Node that) {
        if (sequence > that.sequence) {
            return 1;
        } else if (sequence == that.sequence) {
            return 0;
        } else {
            return -1;
        }
    }

    public int getSequence() {
        return sequence;
    }

    public void setSequence(int sequence) {
        this.sequence = sequence;
    }

    public String getId() {
        return id;
    }

    public String getDir() {
        return dir;
    }

    public void setDir(String dir) {
        this.dir = dir;
    }

}
